﻿using System;
using System.Collections.Generic;
using System.Text;
using Draco.Commons.NamedObject.Configuration;
using Draco.Commons.Reflection;

namespace Draco.Commons.NamedObject
{
    /// <summary>
    /// 命名对象
    /// </summary>
    public class NamedObjects
    {
        private static Object LockObject = new object();
        
        /// <summary>
        /// 获取命名对象
        /// </summary>
        /// <param name="Name"></param>
        /// <returns></returns>
        public static Object GetNamedObject(string Name)
        {
            if (String.IsNullOrEmpty(Name))
                return null;
            NamedObjectItemConfiguration Config = ObjectConfigCache.Cache[Name];
            if (Config == null)
                throw new ArgumentException("未配置名称为'" + Name + "'的对象");

            Object Target = ObjectCache.Cache[Name];
            if (!Config.Single || Target==null)//创建对象
            {
                lock (LockObject)
                {
                    Target = CreateObject(Config);
                    ObjectCache.Cache[Name] = Target;
                }
            }
            return Target;
        }

        /// <summary>
        /// 创建Object对象
        /// </summary>
        /// <param name="Config"></param>
        /// <returns></returns>
        private static Object CreateObject(NamedObjectItemConfiguration Config)
        {
            Class cls = Class.ForName(Config.TypeName);
            return cls.NewInstance();
        }
    }
}
